package mpo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Utility {
    
    public static String toSHA1(byte[] convertme) {
       final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        }
        catch(NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] buf = md.digest(convertme);
        char[] chars = new char[2 * buf.length];
        for (int i = 0; i < buf.length; ++i) {
            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
        }
        return new String(chars);
    }
    
    public static boolean canBeAPesel(String pesel){
        if (pesel.length() != 11) return false;
        for(char c: (pesel.toCharArray()) ) {
            if ( ! Character.isDigit(c)) return false;
        }
        return true;
    }
    public static boolean isNipValid(String NIP){
        if ((NIP.length() == 13) || (NIP.length() == 10)) {
            return true;
         }
        return false;
    }
    
    public static String i(String NIP){
        return NIP.replaceAll("-", "");
    }
 
    public static String checkNIP(String NIP) {
         if (NIP.length() == 13) {
            System.out.println(NIP);
            NIP = NIP.replaceAll("-", "");
            System.out.println(NIP);
            return NIP;
        }
         
        if (NIP.length() != 10) {
            System.out.println("Zbyt krotki NIP");
            return null;
        }
        return NIP;
    }
    
    
    public static boolean sendEmailViaSSL(final String username,final String password, String fromAdress,
            String toAdress, String subject, String text) throws Exception {
        
        Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.socketFactory.port", "465");
	props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.port", "465");
 
	Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
            	protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username,password);
            	}
            }
        );
 
	try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAdress));
            message.setRecipients(Message.RecipientType.TO,
		InternetAddress.parse(toAdress));
            
            message.setSubject(subject);
            message.setText(text);
                
            Transport.send(message);
 
            System.out.println("Wysłano");
            return true;
	} catch (MessagingException e) {
            //System.err.println(e);
            throw new RuntimeException(e);
	}
    }
    
    public static boolean sendEmailViaTLS(final String password, final String fromAdress,
            String toAdress, String subject, String text) throws Exception {
        
        Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.port", "587");
 
	Session session = Session.getInstance(props,
	  new javax.mail.Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(fromAdress, password);
		}
	  });
 
	try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAdress));
            message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(toAdress));
            message.setSubject(subject);
            message.setText(text);
 
            Transport.send(message);
 
            System.out.println("Wysłano");
            return true;
       	} catch (MessagingException e) {
            System.err.println(e);
            throw new RuntimeException(e);
	}
    }
    
    
    public static boolean isInternetWorks(boolean talktive){
        if(talktive) System.out.println("Test podniesionego interfejsu");
        boolean result = false;
        boolean ifSkipTest = false;
        String strona = "";
        String sport ="";
        String sIfSkipTest ="";
        int port = 80;
        Properties prop = new Properties();
        InputStream input = null;
        try {
            input = new FileInputStream("siteTest.properties");
            prop.load(input);
            strona = prop.getProperty("URL");
            sport = prop.getProperty("PORT");
            sIfSkipTest = prop.getProperty("SKIP_TEST");
            
        } catch (IOException ex) {
            strona = "google.com";
            sport = "80";
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try{
                    port = Integer.valueOf(sport);
                }
                catch(Exception e){
                    port = 80;
                }
                try{
                    ifSkipTest = Boolean.valueOf(sIfSkipTest);
                }
                catch(Exception e){
                    ifSkipTest = false;
                }
            }
            if (strona==null) strona="google.com";
        }
        
        if(ifSkipTest)return true;
        if(talktive) System.out.println("Test na: "+ strona + " " + port);
        if (isThisSiteRespons(strona, port, talktive)) result = true;
 
        return result;
    }
    
    private static boolean isThisSiteRespons(String host, int port, boolean talkative){
        try(Socket s = new Socket(host,port)){
            InputStream is = s.getInputStream();
            Scanner scanner = new Scanner(is);
            if(talkative){
                System.out.println("url jest ->: " + host);
            }
            return true;
        }catch(Exception e){
            if(talkative){
                System.err.println("url nieodpowiedzial ->: " + host);
            }
            return false;
        }
    }
}
